package com.back.end.interceptor;

import com.back.end.enums.ResultCode;
import com.back.end.exception.AuthException;
import com.back.end.utils.token.JwtUtil;
import com.back.end.utils.redis.RedisUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

public class JwtInterceptor implements HandlerInterceptor {
    Logger logger = LoggerFactory.getLogger(JwtInterceptor.class);

    @Resource
    RedisUtil redisUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        logger.info(request.getRequestURI());
        //如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        String clientType = request.getHeader("clientType");
        if (clientType.equals("MP")) {
            String accessToken = request.getHeader("accessToken");
            logger.info("此处测试是否拿到了token：" + accessToken);
            if (accessToken == null || redisUtil.get("accessToken") == null || accessToken.equals("")) {
                throw new AuthException(ResultCode.ACCESS_TOKEN_NOT_EXIT);
            }

            //验证 token
            JwtUtil.checkSign(accessToken);

            //验证通过后， 这里测试取出JWT中存放的数据
            //获取 token 中的 userId
            String userId = JwtUtil.getUserId(accessToken);
            logger.info("id : " + userId);
            //获取 token 中的其他数据
            Map<String, Object> info = JwtUtil.getInfo(accessToken);
            return true;
        } else if (clientType.equals("Web")) {
            String token = request.getHeader("token");
            logger.info("此处是否拿到了token：" + token);
            if (token == null || redisUtil.get("token") == null) {
                throw new AuthException(ResultCode.TOKEN_NOT_EXIT);
            }

            //验证 token
            JwtUtil.checkSign(token);

            //验证通过后， 这里测试取出JWT中存放的数据
            //获取 token 中的 userId
            String userId = JwtUtil.getUserId(token);
            logger.info("id : " + userId);
            //获取 token 中的其他数据
            Map<String, Object> info = JwtUtil.getInfo(token);
            info.forEach((k, v) -> System.out.println(k + ":" + v));
            return true;
        } else {
            throw new RuntimeException("非法请求");
        }
    }
}